package com.monad.firemoth.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.monad.firemoth.common.utils.Result;
import com.monad.firemoth.system.entity.LoginParam;
import com.monad.firemoth.system.entity.User;
import com.monad.firemoth.system.service.LoginService;
import com.monad.firemoth.system.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author 单C胞生物
 * @version 1.0.0
 * @date 2024/4/20 22:00
 * @description 登录 服务实现类
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;

    @Override
    public Result login(LoginParam loginParam, HttpServletRequest request) {
        String password = SaSecureUtil.md5BySalt(loginParam.getPassword(), "firemoth");
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, loginParam.getUsername()).eq(User::getPassword, password));
        if (ObjectUtil.isEmpty(user)) {
            return Result.error("用户或密码错误!");
        }
        if (user.getEnabled() == 1) {
            return Result.error("账号已被禁用!");
        }
        StpUtil.login(user.getUserId());
        StpUtil.getSessionByLoginId(StpUtil.getLoginId()).set("loginUser", user);
        return Result.success("登录成功!", StpUtil.getTokenValue());
    }

    @Override
    public Result register(LoginParam loginParam) {
        String password = SaSecureUtil.md5BySalt(loginParam.getPassword(), "firemoth");
        if (Objects.isNull(userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, loginParam.getUsername())))) {
            User user = new User();
            user.setUsername(loginParam.getUsername());
            user.setPassword(password);
            user.setNickname(loginParam.getUsername());
            userService.save(user);
            return Result.success("注册成功!");
        } else {
            return Result.error("该账号已存在!");
        }
    }

    @Override
    public Result logout() {
        StpUtil.logout();
        return Result.success("注销成功!");
    }

}
